package com.iot08.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot08.api.constant.Constant;
import com.iot08.api.vo.request.AppRecordReqVO;
import com.iot08.api.vo.request.CmsgReqVO;
import com.iot08.common.config.mongodb.query.UpdateVO;
import com.iot08.common.entity.app.Account;
import com.iot08.common.entity.app.Device;
import com.iot08.common.entity.app.DeviceAppRecord;
import com.iot08.common.entity.app.DeviceCmsg;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class DeviceAppRecordService extends BaseService<DeviceAppRecord> {

    @Resource
    private AccountService accountService;

    @Resource
    private DeviceService deviceService;

    /**
     * 生成应用使用记录
     * @author: Weichao
     * @version 1.0
     */
    public DeviceAppRecord add(String imei, JSONObject tcpCMDData) {
        DeviceAppRecord deviceAppRecord = new DeviceAppRecord();
        String appName = tcpCMDData.getString("appName");
        String recordID = tcpCMDData.getString("recordID");
        deviceAppRecord.setId(DigestUtils.md5Hex(appName + recordID).toLowerCase());
        deviceAppRecord.setAppName(appName);
        deviceAppRecord.setImei(imei);
        deviceAppRecord.setStartTime(tcpCMDData.getLong("startTime"));
        deviceAppRecord.setEndTime(tcpCMDData.getLong("endTime"));
        deviceAppRecord.setExpiryAt(DateUtil.getSystemExpiryAt());
        return this.save(deviceAppRecord);
    }


    /**
     * 获取应用使用记录
     * @param imei
     * @param delTime 此时间之前的不查询
     * @param dateStr 指定的日期 yyyy-MM-dd
     * @param page 当前页
     * @param num 分页查询的 个数
     * @time: 12/13/21 5:34 PM
     * @author: Weichao
     * @version 1.0
     */
    public List<DeviceAppRecord> listData(String imei, Double delTime, String dateStr, int page , int num) {
        String startTimeStr = dateStr + " 000000";
        String endTimeStr = dateStr + " 235959";
        Long startTime = DateUtil.nowTimestampToLong();
        Long endTime = DateUtil.nowTimestampToLong();
        try {
            //毫秒
            startTime = DateUtil.strToDate(startTimeStr, "yyyy-MM-dd HHmmss").getTime()/1000;
            endTime = DateUtil.strToDate(endTimeStr, "yyyy-MM-dd HHmmss").getTime()/1000;
            if(endTime <= delTime ){
                // delTime 此时间之前的不查询,返回空
                return new ArrayList<>();
            }
        }catch (Exception e){
            log.error("获取应用使用记录 时间处理 错误:"+e.getMessage(), e);
            return new ArrayList<>();
        }


        Criteria criteria = Criteria.where("i").is(imei);

        // imei 且 大于等于(gte) 删除时间的


        //指定日期
        if( delTime > startTime){
            startTime = delTime.longValue();
        }
        criteria.and("startTime").gte(startTime).lte(endTime);

        Query query = new Query(criteria);
        // 排序, 分页
        List<DeviceAppRecord> records = this.find(query.with(Sort.by(Sort.Order.desc("startTime"))).skip(page*num).limit(num));
        return records;
    }


    /**
     * 删除对应Id的应用使用记录
     * @param delIds
     * @time: 12/14/21 9:38 AM
     * @author: Weichao
     * @version 1.0
     */
    public void delRecordWithIds(String delIds) {
        JSONArray idArr = JSON.parseArray(delIds);
//        //删除指定id
//        Set<ObjectId> objectIdList = new HashSet<>();
//        for (int i = 0; i < idArr.size(); i++) {
//            if (ObjectId.isValid(idArr.getString(i))) {
//                objectIdList.add(new ObjectId(idArr.getString(i)));
//            }
//        }
//        if (objectIdList.size() > 0) {
//            this.delByIds(objectIdList);
//        }
        this.delByIds(idArr);
    }

    /**
     * 根据imei 号清空对应的记录
     * @param imei
     * @time: 12/15/21 6:13 PM
     * @author: Weichao
     * @version 1.0
     */
    public void delRecordWithImei(String imei) {
        this.delByQuery(new Query(Criteria.where("i").is(imei)));
    }

    /**
     * 查/改/删代收短信
     * @param imei
     * @param vo
     * @time: 12/13/21 4:08 PM
     * @author: Weichao
     * @version 1.0
     */
    public ResponseMap recordData(String imei, AppRecordReqVO vo) {
        JSONObject res = new JSONObject();
        if(vo.getOption().equals("get")){
            //查
            Account account = accountService.findById(vo.getOpenid());
            Map<String, Object> devBingV = account.getDeviceMap().get(imei);
            //该账号 绑定此设备的时间
            Double bindTime = new Double(devBingV.get("t").toString());
            Integer page = vo.getPage();
            Integer num = vo.getNum();
            List<DeviceAppRecord> deviceAppRecords = this.listData(imei, bindTime, vo.getDateStr(), page, num);
            List<Object> msgList = new ArrayList<>();
            for (DeviceAppRecord item: deviceAppRecords) {
                JSONObject temp = new JSONObject();
                temp.put("id",item.getId());
                temp.put("appName",item.getAppName());
                temp.put("startTime",item.getStartTime());
                temp.put("endTime",item.getEndTime());
                msgList.add(temp);
            }
            res.put("msgList", msgList);

//        }else if (vo.getOption().equals("change")){
//            //改
//            //直接更新到 设备表中去,不比对了 (减少一次查询)
//            UpdateVO updateVO = new UpdateVO();
//            updateVO.set("cmsgStatus", vo.getCmsgStatus());
//            deviceService.updateById(imei, updateVO);
//            // 下发修改代收短信开关的 指令
////            JSONObject kafkaJson = new JSONObject();
////            kafkaJson.put("cmsgStatus", vo.getCmsgStatus());
////            kafkaService.emitDeviceDemand(imei, ConstKafka.DEVICE_TYPE_124, kafkaJson);
        }else if (vo.getOption().equals("del")){
            //删
            this.delRecordWithIds(vo.getDelIds());
        }
        return ResponseMap.success(res);
    }
}
